from flask import Blueprint, request
from utilsapp.common import parsing_permissions
from utilsapp.mysql_con import db_connect
from utilsapp import common

authority = Blueprint('authority', __name__)


@authority.route('/getTree')
def get_tree_list():
    index_d = request.args.get("id")
    if index_d is None:
        index_d = 0
    s0 = f"select id as value,parent as pid,name as label ,type from regionlevel"
    res = db_connect(s0)
    res_data = res.get("data")
    res = common.build_tree(res_data, index_d)
    return {"data": res, 'msg': '查询成功', 'status': 200}


@authority.route('/getGroup')
def get_group():
    flag = parsing_permissions(request)  # 获取用户权限
    data_id = flag['dataId']  # 数据权限 dataID

    if data_id == 0:  # 此时为超级管理员 可以返回所有的集团名称
        sql = f"""SELECT id,name as group_name from regionlevel WHERE type = 'group'"""
        result = {
            "status": 200,
            "groupList": db_connect(sql)["data"],
            "msg": "查询成功"
        }
    else:
        sql = f"""SELECT id,type,name as group_name from regionlevel WHERE id = {data_id}"""
        res = db_connect(sql)["data"][0]
        if res["type"] == "group":
            result = {
                "status": 200,
                "msg": "查询成功",
                "groupList": [{
                    "group_name": res["group_name "],
                    "id": res["id"]
                }]
            }
        else:
            result = {
                "status": 202,
                "msg": "您无权限访问集团信息"
            }
    return result


@authority.route('/getCompany', methods=['POST'])
def common_company():
    id = request.json.get('id')
    sql = f"""SELECT id,name as company_name FROM regionlevel WHERE parent = {id} """
    res = {
        "status": 200,
        "msg": "查询成功",
        "companyList": db_connect(sql)["data"]
    }
    return res


@authority.route('/getFactory', methods=['POST'])
def common_factory():
    id = request.json.get('id')
    sql = f"""SELECT id,name as factory_name FROM regionlevel WHERE parent = {id} """
    res = {
        "status": 200,
        "msg": "查询成功",
        "factoryList": db_connect(sql)["data"]
    }
    return res


@authority.route('/getZone', methods=['POST'])
def common_zone():
    id = request.json.get('id')
    sql = f"""SELECT id,name as zone_name FROM regionlevel WHERE parent = {id} """
    sql1 = f"""SELECT id,name as factory_name FROM regionlevel WHERE id = {id} """
    res = {
        "status": 200,
        "msg": "查询成功",
        "factoryList": db_connect(sql1)["data"],
        "zoneList": db_connect(sql)["data"]
    }
    return res


@authority.route('/getZoneItem')
def get_zone():
    flag = parsing_permissions(request)  # 获取用户权限
    data_id = flag['dataId']  # 数据权限 dataID

    sql = f"""SELECT id,name FROM regionlevel where id = {data_id}"""
    return db_connect(sql)


